/**
  ************************************* Copyright ******************************
  * FileName   : at24cxx.c
  * Version    : v1.0
  * Author     : yychao
  * Date       : 2024-03-05
  * Description:
  * Function List:
  	1. ....
  	   <version>:
  <modify staff>:
  		  <data>:
   <description>:
  	2. ...
  ******************************************************************************
 */
#include "at24cxx.h"
#include "iic.h"
#include "systick.h"
#include "log.h"
#include <rtthread.h>

//在AT24CXX指定地址读出一个数据
//ReadAddr:开始读数的地址
//返回值  :读到的数据
uint8_t At24cxxReadOneByte(uint16_t ReadAddr)
{
    uint8_t temp=0;
    uint8_t addrh = 0;
    uint8_t addrl = 0;

    addrh=ReadAddr>>8;
    addrl=ReadAddr&0xff;

    iic_start();
    iic_send_byte(EE_DEV_ADDR);
    iic_wait_ack();
    iic_send_byte(addrh);
    iic_wait_ack();
    iic_send_byte(addrl);
    iic_wait_ack();
    iic_start();
    iic_send_byte(EE_DEV_ADDR + 1);
    iic_wait_ack();
    temp = iic_read_byte(0);
    iic_stop();
    LOG_KEY("AT24CxxRead:[%d %x]\r\n", ReadAddr, temp);
    return temp;
}


//在AT24CXX指定地址写入一个数据
//WriteAddr  :写入数据的目的地址
//DataToWrite:要写入的数据
void At24cxxWriteOneByte(uint16_t WriteAddr, uint8_t DataToWrite)
{
    uint8_t temp=0;
    uint8_t addrh = 0;
    uint8_t addrl = 0;

    addrh=WriteAddr>>8;
    addrl=WriteAddr&0xff;

    iic_start();
    iic_send_byte(EE_DEV_ADDR);
    iic_wait_ack();
    iic_send_byte(addrh);
    iic_wait_ack();
    iic_send_byte(addrl);
    iic_wait_ack();
    iic_send_byte(DataToWrite);
    iic_wait_ack();
    iic_stop();
    rt_thread_delay(15);
#if 1
    iic_start();
    iic_send_byte(EE_DEV_ADDR);
    iic_wait_ack();
    iic_send_byte(addrh);
    iic_wait_ack();
    iic_send_byte(addrl);
    iic_wait_ack();
    iic_start();
    iic_send_byte(EE_DEV_ADDR + 1);
    iic_wait_ack();
    temp = iic_read_byte(0);
    iic_stop();
    if(temp != DataToWrite) {
        LOG_KEY("AT24CxxWrite Failed\r\n");
    } else {
        LOG_KEY("AT24CxxWrite:[%d %x] Is Finished\r\n", WriteAddr, DataToWrite);
    }
#endif
}

